package cn.minhx.domain.trade.service.lock.filter;

import cn.minhx.domain.trade.adapter.repostitory.ITradeRepository;
import cn.minhx.domain.trade.moedel.entity.GroupBuyActivityEntity;
import cn.minhx.domain.trade.moedel.entity.TradeLockRuleCommandEntity;
import cn.minhx.domain.trade.moedel.entity.TradeLockRuleFilterBackEntity;
import cn.minhx.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import cn.minhx.types.design.link.multi.handler.ILogicHandler;
import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 用户参与限制，规则过滤
 *
 * @author min
 */
@Slf4j
@Service
public class UserTakeLimitRuleFilter
		implements
			ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {

	@Resource
	private ITradeRepository repository;

	@Override
	public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter,
			TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
		log.info("交易规则过滤-用户参与次数校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());
		GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();
		// 查询用户在一个拼团活动上参与的次数
		Integer count = repository.queryOrderCountByActivityId(requestParameter.getActivityId(),
				requestParameter.getUserId());
		if (null != groupBuyActivity.getTakeLimitCount() && count >= groupBuyActivity.getTakeLimitCount()) {
			log.info("用户参与次数校验，已达可参与上限 activityId:{}", requestParameter.getActivityId());
			throw new AppException(ResponseCode.E0103);
		}
		return TradeLockRuleFilterBackEntity.builder().userTakeOrderCount(count).build();
	}
}
